%% @author Carlos Abalde <carlos.abalde@gmail.com>
%% @doc    Global configuration manager.

%%%----------------------------------------------------------------------
%%%
%%% EMC, Copyright (C) 2009 Carlos Abalde
%%%
%%% This program is free software; you can redistribute it and/or
%%% modify it under the terms of the GNU General Public License as
%%% published by the Free Software Foundation; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%%% General Public License for more details.
%%%
%%% You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
%%% 02111-1307 USA
%%%
%%%----------------------------------------------------------------------

-module(emc.util.config).

-import(lists).
-import(erlang).
-import(application).
-import(erl_scan).
-import(erl_parse).
-import(erl_eval).
-import(emc.util.util).

%% API
-export([get/1, get/2]).

%%%-----------------------------------------------------------------------------
%%% API
%%%-----------------------------------------------------------------------------

%%
%%
%%
get(Name) ->
    case do_get(Name) of
	{ok, Value}          -> Value;
	{error, parse_error} -> throw({'EXIT', {bad_formatted_config_item, Name}});
	{error, not_found}   -> throw({'EXIT', {undefined_config_item, Name}})
    end.

%%
%%
%%
get(Name, Default) ->
    case do_get(Name) of
	{ok, Value} -> Value;
	_           -> Default
    end.

%%%-----------------------------------------------------------------------------
%%% Internal implementation
%%%-----------------------------------------------------------------------------

%%
%%
%%
do_get(Name) ->
    case application:get_env(emc, util:a2a(Name)) of
	{ok, Value} ->
	    case catch do_get_aux(Value) of
		{'EXIT', _} -> {error, parse_error};
		TermValue   -> {ok, TermValue}
	    end;
	undefined   ->
	    {error, not_found}
    end.

%%
do_get_aux(Value) ->
    {ok, ValueTokens, _} = erl_scan:string(Value ++ "."),
    {ok, [Expr]} = erl_parse:parse_exprs(ValueTokens),
    {value, TermValue, _} = erl_eval:exprs([Expr], []),
    TermValue.
